package com.happle.gcmclient;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;

import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.happle.gcmclient.backendmanager.BackendManager;
import com.happle.gcmclient.backendmanager.task.UpdateLanguageTask;
import com.happle.gcmclient.config.CommonUtilities;
import com.happle.gcmclient.config.Constants;
import com.happle.gcmclient.config.GlobalValue;
import com.happle.gcmclient.managers.LngManager;
import com.happle.gcmclient.obj.LngObj;
import com.happle.gcmclient.utility.XMLParserUtility;

public class SplashActivity extends BaseActivity {

	protected UpdateLanguageTask updLngTask;
	private XMLParserUtility xmlParser;
	private ArrayList<LngObj> listLanguage;
	private LngManager languageManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		setDefaultLanguage();
		enableStrictMode();
		// maybe it's better to send it in BaceActivity?
		// No need : It can only need in Splash , and MessageListActivity(In
		// case : user start app from a notification )
		startSyncService();
		if (CommonUtilities.getInstance(self).isRegisteredSharedPref(self)) {
			GlobalValue.registerId = CommonUtilities.getInstance(self)
					.pullPreferences(self, CommonUtilities.REGISTRATION_ID);
			try {
				int status = Integer.parseInt(CommonUtilities.getInstance(self)
						.pullPreferences(self, Constants.IS_ONLINE));
				proceedStatus(self, status);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			registerClient();
		}

		if (!CommonUtilities.getInstance(self).getBooleanValue(
				Constants.LNG_TBL_FILLED_NAME)) {
			new ReadLanguageTask().execute();

		} else {
			// Go Main Screen after 2s
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					gotoActivity(self, MainActivity.class);
					finish();
				}
			}, 2000);
		}
	}

//	private void test() {
//		
//		ArrayList<ArrayList<String>> fullData=new ArrayList<ArrayList<String>>(
//		(new ArrayList(Arrays.asList("a","b"));
//	}
//
//	private ArrayList<String> combineChildItem(ArrayList<String> inputArray,
//			ArrayList<ArrayList<String>> dataSet) {
//		ArrayList<String> result = null;
//		StringBuilder b;
//		for (String item : inputArray) {
//			result = new ArrayList<String>();
//			b = new StringBuilder();
//			b.append(item);
//			for (ArrayList<String> arrayList : dataSet) {
//				for (String lastChild : arrayList) {
//					b.append(lastChild);
//				}
//			}
//			result.add(b.toString());
//		}
//		ArrayList<String> dataSetTemp = null;
//		if (dataSet.size() > 2) {
//			dataSetTemp = dataSet.get(0);
//			dataSet.remove(0);
//			combineChildItem(dataSetTemp, dataSet);
//		}
//		return result;
//
//	}

	private void setDefaultLanguage() {

		// Get device language code
		String localeCode = CommonUtilities.getInstance(self).getStringValue(
				CommonUtilities.SETTING_LANGUAGE_CODE);

		if (localeCode.equalsIgnoreCase(""))
			localeCode = Locale.getDefault().getLanguage();

		Locale locale = new Locale(localeCode);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		onConfigurationChanged(config);
		getBaseContext().getResources().updateConfiguration(config,
				getBaseContext().getResources().getDisplayMetrics());

	}

	/**
	 * Allow read network state when doing background task
	 */
	public static void enableStrictMode() {

		try {
			@SuppressWarnings("rawtypes")
			Class strictModeClass = Class.forName("android.os.StrictMode");
			@SuppressWarnings("rawtypes")
			Class strictModeThreadPolicyClass = Class
					.forName("android.os.StrictMode$ThreadPolicy");
			Object laxPolicy = strictModeThreadPolicyClass.getField("LAX").get(
					null);
			@SuppressWarnings("unchecked")
			Method method_setThreadPolicy = strictModeClass.getMethod(
					"setThreadPolicy", strictModeThreadPolicyClass);
			method_setThreadPolicy.invoke(null, laxPolicy);
		} catch (Exception e) {
		}
	}

	public class ReadLanguageTask extends AsyncTask<Void, Void, Integer> {

		@Override
		protected Integer doInBackground(Void... params) {
			xmlParser = new XMLParserUtility(self);
			languageManager = new LngManager(self);
			listLanguage = xmlParser.getLangugeList(self);
			// You can insert into database .then query later
			for (int i = 0; i < 5; i++) {
				if (languageManager.addListLanguage(listLanguage)) {
					CommonUtilities.getInstance(self).putBooleanValue(
							Constants.LNG_TBL_FILLED_NAME, true);
				}
				i = 5;
			}
			// String deviceLanguage = Locale.getDefault().getLanguage();
			String deviceLanguage = Locale.getDefault().toString()
					.substring(0, 2).toUpperCase(Locale.ENGLISH);
			LngObj newLngObj = new LngObj(deviceLanguage, deviceLanguage, true,
					false);
			newLngObj.set_is_sent(updateLanguage(newLngObj) == 1);
			if (!languageManager.updateLngStatus(newLngObj)) {
				Toast.makeText(self, deviceLanguage, Toast.LENGTH_LONG).show();
				languageManager.updateLngSettings(new LngObj(
						Constants.LANGUAGE_ID, Constants.LANGUAGE_ID, true,
						false));
			}
			return 1;

		}

		//
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d(TAG, "Read language finish c");
			gotoActivity(self, MainActivity.class);
			finish();
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			Log.d(TAG, "READ LANGUAGE : CANCEL");
		}
	}

	

	@Override
	public void onDestroy() {
		GCMRegistrar.onDestroy(this);
		super.onDestroy();
	}

	private int updateLanguage(LngObj lngObj) {
		int result = Constants.FAILED;
		if (GlobalValue.registerId != "") {
			try {
				BackendManager bManager = new BackendManager();
				result = bManager
						.updateLanguage(lngObj, GlobalValue.registerId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
